package 尚硅谷.juc.test18;

import lombok.SneakyThrows;

import java.util.concurrent.TimeUnit;

public class Test18 {

    public static void main(String[] args) {
         String lockA="lockA";
         String lockB="lockB";
         new Thread(new HoldLock(lockA,lockB),"AA").start();
         new Thread(new HoldLock(lockB,lockA),"BB").start();
    }
}

/**
 * 资源类
 */
class HoldLock implements Runnable{

    private String lockA;
    private String lockB;

    public HoldLock(String lockA, String lockB) {
        this.lockA = lockA;
        this.lockB = lockB;
    }

    @Override
    public void run() {
        synchronized (lockA){
            try {
                System.out.println(Thread.currentThread().getName()+"持有："+lockA+",尝试获取"+lockB);
                TimeUnit.SECONDS.sleep(2);
                System.out.println("============================================");
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            synchronized (lockB){
                System.out.println("-------------------------------------------");
                System.out.println(Thread.currentThread().getName()+"持有："+lockB+",尝试获取"+lockA);
            }
        }
    }
}
